<template>
  <div class="discover-view">
    <div class="container">
      <div class="parent-categories-nav" v-if="parentCategories.length > 0">
        <el-tabs v-model="activeParentCate" @tab-change="handleParentCateChange" class="parent-tabs">
          <el-tab-pane v-for="parentCate in parentCategories" :key="parentCate" :label="parentCate"
            :name="parentCate" />
        </el-tabs>
      </div>

      <div class="content-wrapper" v-if="activeParentCate">
        <aside class="sidebar" v-if="subCategories.length > 0">
          <el-card class="category-card" shadow="never">
            <template #header>
              <div class="card-header">
                <el-icon>
                  <FolderOpened />
                </el-icon>
                <span>分类导航</span>
              </div>
            </template>
            <div class="category-list">
              <div v-for="(item, index) in subCategories" :key="item.id" class="category-item"
                :class="{ 'active': activeSubCateIndex === index }" @click="tabFn(index)">
                <span class="category-name">{{ item.cate_name }}</span>
                <el-icon class="category-arrow">
                  <ArrowRight />
                </el-icon>
              </div>
            </div>
          </el-card>
        </aside>

        <main class="main-content">
          <div class="article-count" v-if="articles.length > 0">
            共找到 <span>{{ articles.length }}</span> 篇文章
          </div>
          <div v-else class="empty-state">
            <el-icon class="empty-icon">
              <Document />
            </el-icon>
            <p>暂无文章</p>
          </div>
          <ListItem :arr="articles" />
        </main>
      </div>

      <div v-else class="empty-categories">
        <el-icon class="empty-icon">
          <FolderOpened />
        </el-icon>
        <p>暂无分类数据</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import ListItem from '@/components/ListItem.vue'
import { useCateStore } from '@/stores/cate'
import { articleList, host } from '@/api/index'
import { FolderOpened, ArrowRight, Document } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const cateStore = useCateStore()

interface IItem {
  id: number
  title: string
  author: string
  content: string
  createAt: string
  src: string
  tag: string
  [key: string]: any
}

interface ICate {
  id: number
  cate: string
  cate_name: string
  cate_url?: string
}

const pageNum = ref<number>(1)
const pageSize = ref<number>(15)
const articles = ref<Array<IItem>>([])
const cate_name = ref<string | undefined>("")
const activeSubCateIndex = ref<number>(0)
const subCategories = ref<ICate[]>([])
const activeParentCate = ref<string>('')
const allCategories = ref<ICate[]>([])

const parentCategories = computed(() => {
  const parentSet = new Set<string>()
  allCategories.value.forEach(item => {
    if (item.cate) {
      parentSet.add(item.cate)
    }
  })
  return Array.from(parentSet).sort()
})

const articleListFn = async () => {
  await articleList({ page_size: pageSize.value, page_num: pageNum.value, cate_name: cate_name.value })
    .then((resData: any) => {
      articles.value = []
      if (resData.code == 200) {
        let { data } = resData
        let arr = data.map((item: IItem) => {
          const date = new Date(item.createAt)
          item.createAt = date.toISOString()
          item.src = host + item.src
          return item
        })
        articles.value = arr
      }
    })
}

const tabFn = (value: number) => {
  activeSubCateIndex.value = value
  cate_name.value = subCategories.value[value]?.cate_name
  router.replace({
    path: '/discover',
    query: {
      parentCate: activeParentCate.value,
      subCate: subCategories.value[value]?.cate_name
    }
  })
}

const handleParentCateChange = (parentCate: string) => {
  activeParentCate.value = parentCate
  loadSubCategories(parentCate)
  router.replace({
    path: '/discover',
    query: {
      parentCate: parentCate
    }
  })
}

const loadSubCategories = (parentCate: string) => {
  const filtered = allCategories.value.filter(item => item.cate === parentCate)
  subCategories.value = filtered
  activeSubCateIndex.value = 0
  if (filtered.length > 0) {
    cate_name.value = filtered[0]?.cate_name
  } else {
    cate_name.value = undefined
    articles.value = []
  }
}

const initCategoryData = async () => {
  await cateStore.cateListFn()
  allCategories.value = cateStore.cates

  const routeParentCate = route.query.parentCate as string
  const routeSubCate = route.query.subCate as string

  if (routeParentCate && parentCategories.value.includes(routeParentCate)) {
    activeParentCate.value = routeParentCate
    loadSubCategories(routeParentCate)

    if (routeSubCate) {
      const subIndex = subCategories.value.findIndex(item => item.cate_name === routeSubCate)
      if (subIndex !== -1) {
        activeSubCateIndex.value = subIndex
        cate_name.value = routeSubCate
      }
    }
  } else if (parentCategories.value.length > 0) {
    const firstParentCate = parentCategories.value[0]
    if (firstParentCate) {
      activeParentCate.value = firstParentCate
      loadSubCategories(firstParentCate)
      router.replace({
        path: '/discover',
        query: {
          parentCate: firstParentCate
        }
      })
    }
  }
}

watch(() => route.query.parentCate, (newParentCate) => {
  if (newParentCate && typeof newParentCate === 'string' && parentCategories.value.includes(newParentCate)) {
    if (activeParentCate.value !== newParentCate) {
      activeParentCate.value = newParentCate
      loadSubCategories(newParentCate)
    }
  }
}, { immediate: true })

watch(() => route.query.subCate, (newSubCate) => {
  if (newSubCate && typeof newSubCate === 'string') {
    const subIndex = subCategories.value.findIndex(item => item.cate_name === newSubCate)
    if (subIndex !== -1 && activeSubCateIndex.value !== subIndex) {
      activeSubCateIndex.value = subIndex
      cate_name.value = newSubCate
    }
  }
})

watch(cate_name, () => {
  if (cate_name.value) {
    articleListFn()
  }
})

onMounted(() => {
  initCategoryData()
})
</script>

<style lang="less" scoped>
@import "../assets/varable.less";

.discover-view {
  min-height: calc(100vh - 300px);

  .parent-categories-nav {
    margin-bottom: 30px;
    background: @bg-white;
    border-radius: 12px;
    padding: 20px;
    box-shadow: @shadow-sm;

    :deep(.parent-tabs) {
      .el-tabs__header {
        margin: 0;
      }

      .el-tabs__nav-wrap {
        &::after {
          display: none;
        }
      }

      .el-tabs__item {
        font-size: 16px;
        font-weight: 500;
        padding: 0 24px;
        height: 44px;
        line-height: 44px;
        color: @text-secondary;
        transition: all 0.3s;

        &:hover {
          color: @primary-color;
        }

        &.is-active {
          color: @primary-color;
          font-weight: 600;
        }
      }

      .el-tabs__active-bar {
        background-color: @primary-color;
        height: 3px;
      }
    }
  }

  .content-wrapper {
    display: flex;
    gap: 30px;
  }

  .sidebar {
    width: 260px;
    flex-shrink: 0;

    .category-card {
      border-radius: 12px;
      position: sticky;
      top: 90px;

      :deep(.el-card__header) {
        padding: 20px;
        background: @bg-primary;
      }

      :deep(.el-card__body) {
        padding: 0;
      }

      .card-header {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 16px;
        font-weight: 600;
        color: @text-primary;

        .el-icon {
          font-size: 20px;
          color: @primary-color;
        }
      }

      .category-list {
        .category-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 15px 20px;
          cursor: pointer;
          transition: all 0.3s;
          border-bottom: 1px solid @border-light;

          &:last-child {
            border-bottom: none;
          }

          .category-name {
            color: @text-secondary;
            font-size: 15px;
            transition: all 0.3s;
          }

          .category-arrow {
            color: @text-light;
            font-size: 16px;
            opacity: 0;
            transition: all 0.3s;
          }

          &:hover {
            background: @primary-lighter;
            transform: translateX(5px);

            .category-name {
              color: @primary-color;
            }

            .category-arrow {
              opacity: 1;
            }
          }

          &.active {
            background: @primary-lighter;
            border-left: 3px solid @primary-color;

            .category-name {
              color: @primary-color;
              font-weight: 600;
            }

            .category-arrow {
              opacity: 1;
              color: @primary-color;
            }
          }
        }
      }
    }
  }

  .main-content {
    flex: 1;
    min-width: 0;

    .article-count {
      padding: 15px 20px;
      background: @bg-white;
      border-radius: 8px;
      margin-bottom: 20px;
      color: @text-secondary;
      font-size: 14px;
      box-shadow: @shadow-sm;

      span {
        color: @primary-color;
        font-weight: 600;
        font-size: 16px;
      }
    }

    .empty-state {
      text-align: center;
      padding: 60px 20px;
      color: @text-light;

      .empty-icon {
        font-size: 64px;
        margin-bottom: 20px;
        opacity: 0.5;
      }

      p {
        font-size: 16px;
        margin: 0;
      }
    }
  }

  .empty-categories {
    text-align: center;
    padding: 100px 20px;
    color: @text-light;

    .empty-icon {
      font-size: 80px;
      margin-bottom: 20px;
      opacity: 0.5;
    }

    p {
      font-size: 18px;
      margin: 0;
    }
  }
}

@media (max-width: 992px) {
  .discover-view {
    .parent-categories-nav {
      padding: 15px;
      margin-bottom: 20px;

      :deep(.parent-tabs) {
        .el-tabs__item {
          font-size: 14px;
          padding: 0 16px;
          height: 40px;
          line-height: 40px;
        }
      }
    }

    .content-wrapper {
      flex-direction: column;
      gap: 20px;
    }

    .sidebar {
      width: 100%;

      .category-card {
        position: static;

        .category-list {
          display: flex;
          flex-wrap: wrap;
          gap: 10px;
          padding: 15px;

          .category-item {
            flex: 0 0 auto;
            padding: 8px 16px;
            border: 1px solid @border-color;
            border-radius: 20px;
            border-bottom: 1px solid @border-color;

            .category-arrow {
              display: none;
            }

            &:hover {
              transform: translateX(0);
              transform: translateY(-2px);
            }

            &.active {
              border-left: 1px solid @primary-color;
              border-color: @primary-color;
            }
          }
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .discover-view {
    .parent-categories-nav {
      padding: 12px;
      margin-bottom: 15px;

      :deep(.parent-tabs) {
        .el-tabs__item {
          font-size: 13px;
          padding: 0 12px;
          height: 36px;
          line-height: 36px;
        }
      }
    }

    .sidebar {
      .category-card {
        :deep(.el-card__header) {
          padding: 15px;
        }

        .category-list {
          padding: 10px;
          gap: 8px;

          .category-item {
            padding: 6px 12px;
            font-size: 14px;
          }
        }
      }
    }

    .main-content {
      .article-count {
        padding: 12px 15px;
        font-size: 13px;
      }
    }
  }
}
</style>
